package com.cyy.springbootinit.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyy.springbootinit.annotation.AuthCheck;
import com.cyy.springbootinit.common.BaseResponse;
import com.cyy.springbootinit.common.DeleteRequest;
import com.cyy.springbootinit.common.ErrorCode;
import com.cyy.springbootinit.common.ResultUtils;
import com.cyy.springbootinit.constant.UserConstant;
import com.cyy.springbootinit.exception.BusinessException;
import com.cyy.springbootinit.exception.ThrowUtils;
import com.cyy.springbootinit.model.dto.systemnotifiaction.SystemNotificationAddRequest;
import com.cyy.springbootinit.model.dto.systemnotifiaction.SystemNotificationEditRequest;
import com.cyy.springbootinit.model.dto.systemnotifiaction.SystemNotificationQueryRequest;
import com.cyy.springbootinit.model.dto.systemnotifiaction.SystemNotificationUpdateRequest;
import com.cyy.springbootinit.model.entity.SystemNotification;
import com.cyy.springbootinit.model.entity.User;
import com.cyy.springbootinit.model.vo.SystemNotificationVO;
import com.cyy.springbootinit.service.SystemNotificationService;
import com.cyy.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
 * 系统通知表接口
 *
 * @author 程序员cyy</a>
 * @from cyy</a>
 */
@RestController
@RequestMapping("/systemNotification")
@Slf4j
public class SystemNotificationController {

    @Resource
    private SystemNotificationService systemNotificationService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建系统通知表
     *
     * @param systemNotificationAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addSystemNotification(@RequestBody SystemNotificationAddRequest systemNotificationAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(systemNotificationAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        SystemNotification systemNotification = new SystemNotification();
        BeanUtils.copyProperties(systemNotificationAddRequest, systemNotification);
        // 数据校验
        systemNotificationService.validSystemNotification(systemNotification, true);
        // todo 填充默认值
        // 写入数据库
        boolean result = systemNotificationService.save(systemNotification);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newSystemNotificationId = systemNotification.getId();
        return ResultUtils.success(newSystemNotificationId);
    }

    /**
     * 删除系统通知表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSystemNotification(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        SystemNotification oldSystemNotification = systemNotificationService.getById(id);
        ThrowUtils.throwIf(oldSystemNotification == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if ( !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = systemNotificationService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新系统通知表（仅管理员可用）
     *
     * @param systemNotificationUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSystemNotification(@RequestBody SystemNotificationUpdateRequest systemNotificationUpdateRequest) {
        if (systemNotificationUpdateRequest == null || systemNotificationUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        SystemNotification systemNotification = new SystemNotification();
        BeanUtils.copyProperties(systemNotificationUpdateRequest, systemNotification);
        // 数据校验
        systemNotificationService.validSystemNotification(systemNotification, false);
        // 判断是否存在
        long id = systemNotificationUpdateRequest.getId();
        SystemNotification oldSystemNotification = systemNotificationService.getById(id);
        ThrowUtils.throwIf(oldSystemNotification == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = systemNotificationService.updateById(systemNotification);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取系统通知表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<SystemNotificationVO> getSystemNotificationVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        SystemNotification systemNotification = systemNotificationService.getById(id);
        ThrowUtils.throwIf(systemNotification == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(systemNotificationService.getSystemNotificationVO(systemNotification, request));
    }

    /**
     * 分页获取系统通知表列表（仅管理员可用）
     *
     * @param systemNotificationQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<SystemNotification>> listSystemNotificationByPage(@RequestBody SystemNotificationQueryRequest systemNotificationQueryRequest) {
        long current = systemNotificationQueryRequest.getCurrent();
        long size = systemNotificationQueryRequest.getPageSize();
        // 查询数据库
        Page<SystemNotification> systemNotificationPage = systemNotificationService.page(new Page<>(current, size),
                systemNotificationService.getQueryWrapper(systemNotificationQueryRequest));
        return ResultUtils.success(systemNotificationPage);
    }

    /**
     * 分页获取系统通知表列表（封装类）
     *
     * @param systemNotificationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SystemNotificationVO>> listSystemNotificationVOByPage(@RequestBody SystemNotificationQueryRequest systemNotificationQueryRequest,
                                                               HttpServletRequest request) {
        long current = systemNotificationQueryRequest.getCurrent();
        long size = systemNotificationQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<SystemNotification> systemNotificationPage = systemNotificationService.page(new Page<>(current, size),
                systemNotificationService.getQueryWrapper(systemNotificationQueryRequest));
        // 获取封装类
        return ResultUtils.success(systemNotificationService.getSystemNotificationVOPage(systemNotificationPage, request));
    }

    /**
     * 分页获取当前登录用户创建的系统通知表列表
     *
     * @param systemNotificationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<SystemNotificationVO>> listMySystemNotificationVOByPage(@RequestBody SystemNotificationQueryRequest systemNotificationQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(systemNotificationQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        long current = systemNotificationQueryRequest.getCurrent();
        long size = systemNotificationQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<SystemNotification> systemNotificationPage = systemNotificationService.page(new Page<>(current, size),
                systemNotificationService.getQueryWrapper(systemNotificationQueryRequest));
        // 获取封装类
        return ResultUtils.success(systemNotificationService.getSystemNotificationVOPage(systemNotificationPage, request));
    }

    /**
     * 编辑系统通知表（给用户使用）
     *
     * @param systemNotificationEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSystemNotification(@RequestBody SystemNotificationEditRequest systemNotificationEditRequest, HttpServletRequest request) {
        if (systemNotificationEditRequest == null || systemNotificationEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        SystemNotification systemNotification = new SystemNotification();
        BeanUtils.copyProperties(systemNotificationEditRequest, systemNotification);
        // 数据校验
        systemNotificationService.validSystemNotification(systemNotification, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = systemNotificationEditRequest.getId();
        SystemNotification oldSystemNotification = systemNotificationService.getById(id);
        ThrowUtils.throwIf(oldSystemNotification == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if ( !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = systemNotificationService.updateById(systemNotification);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
